package com.ktjy.examination.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.examination.entity.Book;
import com.ktjy.examination.entity.vo.R;
import com.ktjy.examination.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/api/book")
public class BookController {
    @Resource
    private BookService bookService;
    
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/types")
    public R getBookTypes() {
        String key = "book:types";
        List<Map<String, Object>> types = (List<Map<String, Object>>) redisTemplate.opsForValue().get(key);
        
        if (types != null) {
            return R.ok(types);  // 如果Redis中存在数据，直接返回
        }
        
        // Redis中不存在数据，创建新的类型列表
        types = new ArrayList<>();
        types.add(Map.of("value", 1, "label", "小说"));
        types.add(Map.of("value", 2, "label", "文学"));
        types.add(Map.of("value", 3, "label", "传记"));
        types.add(Map.of("value", 4, "label", "艺术"));
        types.add(Map.of("value", 5, "label", "少儿"));
        types.add(Map.of("value", 6, "label", "经济"));
        types.add(Map.of("value", 7, "label", "管理"));
        types.add(Map.of("value", 8, "label", "科技"));
        
        // 将数据存入Redis
        redisTemplate.opsForValue().set(key, types, 24, TimeUnit.HOURS);
        return R.ok(types);
    }

    @GetMapping("/list")
    public R selectPage(
            @RequestParam(required = false) Integer bookType,
            @RequestParam(required = false) String bookName,
            @RequestParam(required = false) Integer isBorrowed,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            IPage<Book> page = bookService.findPageVo(bookType, bookName, isBorrowed, pageNo, pageSize);
            return R.ok(page);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("获取记录失败: " + e.getMessage());
        }
    }
    @PostMapping("/borrow")
    public R borrowBook(@RequestBody Map<String, Long> params) {
        Long bookId = params.get("bookId");
        if (bookId == null) {
            return R.fail("图书ID不能为空");
        }
        boolean success = bookService.borrowBook(bookId);
        return success ? R.ok("借阅成功") : R.fail("借阅失败");
    }
}
